package com.netbao.sys.service.impl;


import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.util.StringUtil;
import com.netbao.model.PageBean;
import com.netbao.model.PageResult;
import com.netbao.model.Result;
import com.netbao.sys.mapper.UserMapper;
import com.netbao.sys.model.Role;
import com.netbao.sys.model.User;
import com.netbao.sys.model.UserExample;
import com.netbao.sys.service.UserService;
import com.netbao.sys.utils.ShiroUtils;
import com.netbao.sys.vomapper.RoleUserVoMapper;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {
    @Resource
    private UserMapper userMapper;
    @Override
    public Result addUser(User user) {
        if(user.getId()==null){
            System.out.println(user.getAccount());
            user.setPassword(ShiroUtils.sha256(user.getPassword(),user.getAccount()));
            System.out.println(user.getPassword());
            userMapper.insertSelective(user);
            return Result.ok();
        }
        userMapper.updateByPrimaryKeySelective(user);
        return Result.ok();
    }

    @Override
    public Result getById(Integer id) {
        return Result.ok(userMapper.getById(id));
    }

    @Override
    public Result upDate(User user) {
        userMapper.upDate(user);
        return Result.ok();
    }

    @Override
    public Result del(Integer id) {
        userMapper.del(id);
        return Result.ok();
    }


    @Override
    public PageResult list(PageBean pageBean, String userName) {
        UserExample example=new UserExample();
        UserExample.Criteria criteria = example.createCriteria().andIsadminEqualTo(false)
                .andEidEqualTo(ShiroUtils.getUserEntity().getEid())
                .andIsdelEqualTo(false);
        if(!StringUtils.isEmpty(userName)){
            criteria.andCnameLike("%"+userName+"%");
        }
        PageHelper.startPage(pageBean.getPage(),pageBean.getRows());
        PageInfo<User> userPageInfo = new PageInfo<>(userMapper.selectByExample(example));
        return new PageResult(userPageInfo.getTotal(),userPageInfo.getList());
    }

    @Resource
    private RoleUserVoMapper roleUserVoMapper;
    @Override
    @Transactional
    public Result saveRole(String roleIds,Long userid,String cnames) {
        roleUserVoMapper.delRole(userid);
        if(!StringUtils.isEmpty(roleIds)) {

            roleUserVoMapper.saveRole(roleIds, userid);
        }
        User user = new User();
        user.setId(userid.intValue());
        user.setRoles(cnames);
        userMapper.updateByPrimaryKeySelective(user);
        return Result.ok();
    }
    @Override
    public PageResult getRole() {
        return new PageResult(null,roleUserVoMapper.getRole());
    }



    @Override
    public Map<String,Object> login(String imageCode, User user, BindingResult bindingResult, HttpSession session) {
        Map<String,Object> map=new HashMap<String,Object>();
        if(StringUtil.isEmpty(imageCode)){
            map.put("success", false);
            map.put("errorInfo", "请输入验证码!");
            return map;
        }
//        if(!ShiroUtils.getSessionAttribute(StatusCode.CHECKCODE).equals(imageCode)){
//            map.put("success", false);
//            map.put("errorInfo", "验证码输入错误!");
//            return map;
//        }
        if(bindingResult.hasErrors()){
            map.put("success", false);
            map.put("errorInfo", bindingResult.getFieldError().getDefaultMessage());
            return map;
        }
        Subject subject= SecurityUtils.getSubject();
        UsernamePasswordToken token=new UsernamePasswordToken(user.getAccount(), user.getPassword());
        try{
            subject.login(token);
//            User account=(User) SecurityUtils.getSubject().getPrincipal();
//            User currentUser=userService.findByAccount(account.getAccount());
//            session.setAttribute("currentUser", currentUser);
            //List<Role> roleList=roleService.findByUserId((long) currentUser.getId().intValue());
            List<Role> roleList = (List<Role>)session.getAttribute("roleList");
            map.put("roleList", roleList);
            map.put("roleSize", roleList.size());
            map.put("success", true);
            //logService.save(new Log(Log.LOGIN_ACTION,"用户登录"));
//            System.out.println("登陆成功");
            return map;
        }catch(Exception e){
            e.printStackTrace();
            map.put("success", false);
            map.put("errorInfo", "用户名或者密码错误!");
            return map;
        }
    }

    @Override
    public Result getFirst() {
        List<Role> roleList =(List<Role>)ShiroUtils.getSessionAttribute("roleList");
        Role role = roleList.get(0);
        switch (role.getCname()){
            case "超级管理员":
                return Result.ok((Object) "/first");
            case "系统管理员":
                return Result.ok((Object) "/first");
            case "车辆管理经理":
                return Result.ok((Object) "");
            case "调度人":
                return Result.ok((Object) "/pro/wayBill");
            case "项目经理":
                return Result.ok((Object) "/first");
            case "财务经理":
                return Result.ok((Object) "");
        }
        return null;
    }

//    @Override
//    public Object list(PageBean pageBean, String userName) {
//        UserExample userExample=null;
//        if(!StringUtils.isEmpty(userName)){
//            userExample.createCriteria().andCnameLike("%"+userName+"%");
//        }
//        PageHelper.startPage(pageBean.getPage(),pageBean.getRows());
//        PageInfo<User> userPageInfo = new PageInfo<>(userMapper.selectByExample(userExample));
//        return new PageResult(userPageInfo.getTotal(),userPageInfo.getEndRow());
//    }
}
